//
//  OperateBtnGroup.swift
//  Slaughter
//
//  Created by Ken on 2019/8/6.
//  Copyright © 2019 zwb. All rights reserved.
//

import UIKit

enum BtnAlignment {
    case right,center,left
}
 
enum BtnColorType {
    // 颜色类型， 边框加文字颜色（背景白）
    // 填充颜色（文字白）
    // 无边框，无背景
    // 特殊的边框型，外框  文字  背景  颜色都不一样
    case border,fill,noneX,specialBorder
}
class OperateBtnGroup: UIView {
    
   private var cRadius_group:CGFloat = 5 // 圆角
    private var bWidth_group:CGFloat = 95
    private var bFont_group:CGFloat = 13
    private var margin:CGFloat = 6
    var clickAction:((Int,String)->())?
    
    
    private var titles:[String]!
    private var imgStrs:[String]!

    private  var btnCType = BtnColorType.border
    private  var btnCTypes:[BtnColorType]? // 优先级高于  btnCType

    private  var btnAlignment = BtnAlignment.right
    private var titleColors: [UIColor]!
    private var borderColors: [UIColor]!
    private var bgColors: [UIColor]!

    var delBtn:UIButton = {
        var v = UIButton()
        v.isHidden = true
        // 给了一个不会显示的  删除中文，为了传递事件的时候用中文处理
        v.setTitle("删除", for: .normal)
        v.setTitleColor(.clear, for: .normal)
        
        v.setBackgroundImage(UIImage(named: "delete_item"), for: .normal)
        return v
    }()
    
    func setTitle(_ titles:[String],colors:[UIColor]? = nil,btnCTypes:[BtnColorType]? = nil) {
        if titles != self.titles {
            self.titles = titles
            if let btnCTypes = btnCTypes {
               self.btnCTypes = btnCTypes
            }
            
            if let colors = colors {
               self.titleColors = colors
                self.borderColors = colors
                self.bgColors = colors

            } else {
                self.titleColors = Array(repeating: Theme.primaryColor(), count: self.titles.count)
                self.borderColors = Array(repeating: Theme.primaryColor(), count: self.titles.count)
                self.bgColors = Array(repeating: Theme.primaryColor(), count: self.titles.count)

            }
            setupSubviews()
        }
    }
    func set4SpecialBorder(_ titles:[String],titltColors:[UIColor],borderColors:[UIColor],bgColors:[UIColor]) {
        if titles != self.titles {
            self.titles = titles
            self.btnCType = .specialBorder
             
            
       
               self.titleColors = titltColors
                self.borderColors = borderColors
                self.bgColors = bgColors

       
            setupSubviews()
        }
    }
   
    
    func setImgs(_ imgStrs:[String],bWidth_group:CGFloat? = nil) {
        if imgStrs != self.imgStrs {
            self.imgStrs = imgStrs
            if let bWidth_group = bWidth_group {
               self.bWidth_group = bWidth_group
            }
            setupImgSubviews()
        }
    }
    init(frame: CGRect = CGRect.zero,btnAlignment:BtnAlignment = .right,imgStrs:[String] = [],bWidth_group:CGFloat? = nil) {
        super.init(frame: frame)
        self.imgStrs = imgStrs
        self.btnAlignment = btnAlignment
   
          if bWidth_group.isSome {
            self.bWidth_group = bWidth_group!
        }
        
        setupImgSubviews()
    }
    // 每个按钮自己有填充方式
    init(frame: CGRect = CGRect.zero,btnAlignment:BtnAlignment = .right,cRadius_group:CGFloat = 5,btnCTypes:[BtnColorType]?,colors:[UIColor]? = nil,titles:[String] = [],bWidth_group:CGFloat? = nil) {
        super.init(frame: frame)
        self.titles = titles
        self.btnAlignment = btnAlignment
        self.cRadius_group = cRadius_group
        if let btnCTypes = btnCTypes {
            self.btnCTypes = btnCTypes
        }
         if let colors = colors {
            self.titleColors = colors
             self.borderColors = colors
             self.bgColors = colors

         } else {
             self.titleColors = Array(repeating: Theme.primaryColor(), count: self.titles.count)
             self.borderColors = Array(repeating: Theme.primaryColor(), count: self.titles.count)
             self.bgColors = Array(repeating: Theme.primaryColor(), count: self.titles.count)

         }
          if bWidth_group.isSome {
            self.bWidth_group = bWidth_group!
        }
        
        setupSubviews()
    }
    // 唯一的填充方式
    init(frame: CGRect = CGRect.zero,btnAlignment:BtnAlignment = .right,cRadius_group:CGFloat = 5,btnCType:BtnColorType? = nil,colors:[UIColor]? = nil,titles:[String] = [],bWidth_group:CGFloat? = nil) {
        super.init(frame: frame)
        self.titles = titles
        self.btnAlignment = btnAlignment
        self.cRadius_group = cRadius_group
        if let btnCType = btnCType {
            self.btnCType = btnCType
        }
         if let colors = colors {
             self.titleColors = colors
              self.borderColors = colors
             self.bgColors = colors
         } else {
             self.titleColors = Array(repeating: Theme.primaryColor(), count: self.titles.count)
             self.borderColors = Array(repeating: Theme.primaryColor(), count: self.titles.count)
             self.bgColors = Array(repeating: Theme.primaryColor(), count: self.titles.count)

              
         }
          if bWidth_group.isSome {
            self.bWidth_group = bWidth_group!
        }
        
        setupSubviews()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // 文字标题
    private func setupSubviews() {
        for subV in self.subviews {
            if subV.isMember(of: UIButton.self) {
                subV.removeFromSuperview()
            }
        }
        self.addSubview(delBtn)
        // 删除转为图片
        if let indx = titles.getIndexFor({ tstr in
            return tstr == "删除"
        }) {
            titles.remove(at: indx)
            delBtn.isHidden = false
            delBtn.addTarget(self, action: #selector(buttonClick(sender:)), for: .touchUpInside)
            delBtn.snp.makeConstraints { (make) in
                make.left.equalTo(self)
                make.width.height.equalTo(28)
                make.centerY.equalTo(self)
            }
        } else {
            delBtn.isHidden = true
        }
        
        var realWidth = bWidth_group
    
        let ziFilter = titles.filter{ $0.count > 5 }
        if ziFilter.count > 0  {
            // 字多 ，按钮不多的情况，搞宽点
            if titles.count < 3 {
                realWidth = 135
            } else {
                realWidth = 105
            }
        }
         if titles!.count > 4 {
             // 按钮太多宽度要小一点
             realWidth = (KSGlobal.screenW - margin * CGFloat(titles!.count + 1) - 15)/CGFloat(titles!.count)
         }
        
        for i in 0..<titles!.count {
            var finalT:BtnColorType!
            if btnCTypes.isSome ,btnCTypes!.count > i {
                finalT = btnCTypes![i]
            } else {
                finalT = self.btnCType
            }
            let btn = creatBtn(tag: i,title: titles![i],titleColor:titleColors[i],borderColor:borderColors[i],bgColor:bgColors[i],btnCType: finalT)
            btn.addTarget(self, action: #selector(buttonClick(sender:)), for: .touchUpInside)
            addSubview(btn)
             
            
            let mmm:CGFloat = (realWidth + margin) *  CGFloat(i)
          if self.btnAlignment == .right {
                btn.snp.makeConstraints { (make) in
                    make.right.equalTo(self).offset(-mmm)
                    make.width.equalTo(realWidth)
                    make.height.equalTo(self)
                }
                
            } else if self.btnAlignment == .left {
                btn.snp.makeConstraints { (make) in
                    make.left.equalTo(self).offset(mmm)
                    make.width.equalTo(realWidth)
                    make.height.equalTo(self)
                }
                 
            } else { // center
                let centerLeftM = (self.ks_width - (realWidth + margin) * CGFloat(titles!.count)) / 2
                btn.snp.makeConstraints { (make) in
                    make.left.equalTo(self).offset( centerLeftM + mmm)
                    make.width.equalTo(realWidth)
                    make.height.equalTo(self)
                }
            }
            
        }
        
    }
    // 图片
    private func setupImgSubviews() {
        for subV in self.subviews {
            if subV.isMember(of: UIButton.self) {
                subV.removeFromSuperview()
            }
        }
        let centerLeftM = (self.ks_width - (bWidth_group + margin) * CGFloat(imgStrs.count)) / 2
        for i in 0..<imgStrs.count {
            let btn = creatImgBtn(tag: i,imgStr: imgStrs[i])
            btn.addTarget(self, action: #selector(buttonClick(sender:)), for: .touchUpInside)
            addSubview(btn)
            let mmm:CGFloat = (bWidth_group + margin) *  CGFloat(i)
          if self.btnAlignment == .right {
                btn.snp.makeConstraints { (make) in
                    make.right.equalTo(self).offset(-mmm)
                    make.width.equalTo(bWidth_group)
                    make.height.equalTo(self)
                }
                
            } else if self.btnAlignment == .left {
                btn.snp.makeConstraints { (make) in
                    make.left.equalTo(self).offset(mmm)
                    make.width.equalTo(bWidth_group)
                    make.height.equalTo(self)
                }
                 
            } else { // center
                btn.snp.makeConstraints { (make) in
                    make.left.equalTo(self).offset( centerLeftM + mmm)
                    make.width.equalTo(bWidth_group)
                    make.height.equalTo(self)
                }
            }
            
        }
        
    }
    @objc private func buttonClick(sender:UIButton) {
        if let closure = clickAction {
            closure(sender.tag,sender.titleLabel!.text.unwrap)
        }
    }
    func creatImgBtn(tag:Int,imgStr:String) -> UIButton {
        let btn:UIButton = UIButton()
        btn.tag = tag
        btn.setBackgroundImage(UIImage(named: imgStr), for: .normal)
          return btn
    }
    func creatBtn(tag:Int,title:String,titleColor:UIColor,borderColor:UIColor,bgColor:UIColor,btnCType:BtnColorType) -> UIButton {
        let btn:UIButton = UIButton()
        btn.tag = tag
        btn.setTitle(title, for: .normal)
        btn.titleLabel?.font = UIFont.boldSystemFont(ofSize: bFont_group)
        btn.layer.borderWidth = 1
        if btnCType == .border {
            btn.layer.borderColor = borderColor.cgColor
            btn.setTitleColor(titleColor, for: .normal)
            btn.backgroundColor = .clear
        }  else if btnCType == .specialBorder {
            btn.layer.borderColor = borderColor.cgColor
            btn.setTitleColor(titleColor, for: .normal)
            btn.backgroundColor = bgColor
        } else if btnCType == .fill {
            btn.layer.borderColor = UIColor.clear.cgColor
            btn.setTitleColor(.white, for: .normal)
            btn.backgroundColor = bgColor
        } else {
            btn.layer.borderColor = UIColor.clear.cgColor
            btn.setTitleColor(titleColor, for: .normal)
            btn.backgroundColor = .clear
        }
        btn.layer.cornerRadius = cRadius_group
         return btn
    }
    
}
